package filter

import (
	"github.com/astaxie/beego/context"
	"h1/controllers"
	"h1/models"
	"h1/utils"
)

var AuthFilter = func(ctx *context.Context) {

	token := ctx.Input.Header("Authorization")
	if token == "" {
		result := controllers.Response(4001, "", "require token")
		_ = ctx.Output.JSON(result, true, true)
		return
	}

	claims, isValid, err := utils.ParaseToken(token)
	if err == nil && isValid {
		var user models.User
		userMod := models.User{}
		err := userMod.Query().Filter("id", claims.UId).One(&user)

		if err != nil {
			ctx.Output.SetStatus(401)
			out := map[string]interface{}{}
			out["msg"] = "err"
			out["code"] = 4001
			_ = ctx.Output.JSON(out, true, true)
			return

		} else {
			if claims.Timestamp == user.Timestamp {
				ctx.Input.SetData("User", user)
				return

			} else {
				result := controllers.Response(4002, "", "账号在其它账号登陆了")
				_ = ctx.Output.JSON(result, true, true)
				return
			}

		}

	}
	out := map[string]interface{}{}
	out["msg"] = "token invalid"
	out["code"] = 4001
	_ = ctx.Output.JSON(out, true, true)
}
